<template>
  <div>
    <div class="tl-attachment-preview" :style="{ height: height + 'px' }">
      <div class="tree-area">
        <div class="bg-title">
          附件列表
        </div>
        <el-tree class="tl-tree" ref="tree" :data="treeList" node-key="id" :default-expand-all="true" highlight-current @node-click="viewAttachment"></el-tree>
      </div>
      <div class="preview-area">
        <div class="bg-title">
          附件预览
        </div>
        <iframe v-show="pdfFile" :src="pdfFile" width="100%" :height="height - 58 + 'px'"></iframe>
      </div>
    </div>
    <div :id="viewerId"></div>
  </div>
</template>

<script>
const { body } = document
import { getAction, deleteAction, putAction } from '@tapui/utils/http'
import Viewer from 'viewerjs'
import 'viewerjs/dist/viewer.min.css'
import axios from '@tapui/utils/request'
export default {
  name: 'TlAttachmentPreview',
  data() {
    return {
      fileList: [],
      treeList: [],
      postData: {
        sourceType: this.sourceType,
        sourceId: this.sourceId
      },
      baseUrl: axios.defaults.baseURL,
      header: {
        Authorization: 'Bearer ' + this.$store.getters.token
      },
      imageViewer: null,
      totalPage: 0,
      pdfFile: null,
      url: {
        upload: '/cbo/attachment/upload',
        download: '/cbo/attachment/download',
        display: '/cbo/attachment/display',
        query: '/meet/record/queryAttachmentList',
        delete: '/cbo/attachment/delete',
        queryCount: '/cbo/attachment/calculateCount',
        viewWord: "/meet/meetManage/previewDownLoad"
      },
      imageArray: ['.jpg', '.bmp', '.png', '.jpeg', '.gif'],
      htmlArray: ['.htm', '.html'],
      pdfArray: ['.pdf'],
      officeArray: ['.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx'],
      height: 400,
      viewerId: 'perview'
    }
  },
  props: {
    outFileList: {
      default: function() {
        return []
      },
      type: Array
    },
    sourceType: {
      type: String,
      default: ''
    },
    sourceId: {
      type: Number,
      default: 0
    },
    extendData: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  computed: {
    imageList() {
      return this.fileList.filter((file) => file.ex_type === 'image')
    }
  },
  methods: {
    open() {
      if (this.outFileList.length > 0) {
        this.fileList = this.outFileList
      }
      this.viewerId = 'perview' + this.sourceType + this.sourceId + Math.floor(Math.random() * 100)
      this.chargeHeight()
      this.loadData()
    },
    loadData() {
      let data = {
        qry_sourceType: this.sourceType,
        qry_sourceId: this.sourceId
      }
      this.fileList = []
      getAction(this.url.query, { ...data, ...this.extendData }).then((res) => {
        if (res.success) {
          this.fileList = res.result
          this.bindTreeList()
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
    },
    chargeHeight() {
      let total = body.getBoundingClientRect().height
      this.height = total - 150
    },
    bindTreeList() {
      let imageParent = { id: 0, icon: 'el-icon-picture', label: '图片', children: [] }
      let pdfParent = { id: -1, icon: 'el-icon-s-management', label: 'PDF文档', children: [] }
      let htmlParent = { id: -2, icon: 'el-icon-platform-eleme', label: '网页', children: [] }
      let officeParent = { id: -3, icon: 'el-icon-s-marketing', label: 'OFFICE文档', children: [] }
      let otherParent = { id: -4, icon: 'el-icon-s-order', label: '其他', children: [] }
      this.fileList.forEach((file) => {
        let fileType = file.filetype.toLowerCase()
        if (this.imageArray.includes(fileType)) {
          file.ex_type = 'image'
          this.asyncDisplay(file)
          imageParent.children.push({ ...file, ...{ label: file.displayname } })
        } else if (this.pdfArray.includes(fileType)) {
          file.ex_type = 'pdf'
          pdfParent.children.push({ ...file, ...{ label: file.displayname } })
        } else if (this.htmlArray.includes(fileType)) {
          htmlParent.children.push({ ...file, ...{ label: file.displayname } })
        } else if (this.officeArray.includes(fileType)) {
          officeParent.children.push({ ...file, ...{ label: file.displayname } })
        } else {
          otherParent.children.push({ ...file, ...{ label: file.displayname } })
        }
      })
      this.treeList = []
      if (imageParent.children.length > 0) {
        this.treeList.push(imageParent)
      }
      if (pdfParent.children.length > 0) {
        this.treeList.push(pdfParent)
      }
      if (htmlParent.children.length > 0) {
        this.treeList.push(htmlParent)
      }
      if (officeParent.children.length > 0) {
        this.treeList.push(officeParent)
      }
      if (otherParent.children.length > 0) {
        this.treeList.push(otherParent)
      }
    },
    async asyncDisplay(file) {
      if (!file.id) return
      let res = await axios({
        url: this.url.download,
        method: 'post',
        data: { attachmentId: file.id },
        responseType: 'arraybuffer'
      })
      file.ex_base64 = 'data:image/png;base64,' + this.$tap.util.bufferToBase64(res)
    },
    viewAttachment(file) {
      if (file.id <= 0) {
        return
      }
      if (!file.ex_type) {
        if (file.filetype === '.DOCX' || file.filetype === '.XLSX' ||
        file.filetype === '.DOC' || file.filetype === '.XLS' ||
        file.filetype === '.PPT' || file.filetype === '.PPTX') {
        this.viewWord(file)
      } else {
        this.handleDownload(file)
      }
      } else if (file.ex_type === 'image') {
        this.viewImage(file)
      } else if (file.ex_type === 'pdf') {
        this.viewPdf(file)
      } else {
        this.handleDownload(file)
      }
    },
    viewWord(file) {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      axios({
        url: this.url.viewWord,
        method: 'post',
        data: { attachmentId: file.id },
        responseType: 'blob'
      }).then((response) => {
        loading.close()
        let url = this.getObjectURL(response)
        this.pdfFile = `/static/plugins/pdfjs/web/viewer.html?file=${url}`
        this.pdfTitle = file.displayname
      }).catch((err) => {
        loading.close()
        // this.$tap.alert(`删除失败：${res.message}`, 'warning')
        if (err && err.response && err.response.status === 417) {
          this.$tap.alert('暂不支持该格式文件查看', 'warning')
        }
      })
    },
    handleDownload(file) {
      axios({
        url: this.url.download,
        method: 'post',
        data: { attachmentId: file.id },
        responseType: 'blob'
      }).then((response) => {
        this.doDownload(response, file)
      })
    },
    doDownload(response, file) {
      var blob = new Blob([response], { type: 'application/octet-stream;charset=utf-8' })
      var tempObjectUrl = window.URL.createObjectURL(blob)
      var aLink = document.createElement('a')
      aLink.style.display = 'none'
      aLink.download = file.displayname
      aLink.href = tempObjectUrl
      document.body.appendChild(aLink)
      aLink.click()
      document.body.removeChild(aLink)
      window.URL.revokeObjectURL(tempObjectUrl)
    },
    getFileExt(fileName) {
      let arr = fileName.split('.')
      if (arr.length === 0) return ''
      else return arr[arr.length - 1].toString().toLowerCase()
    },
    viewImage(file) {
      if (!this.imageViewer) {
        this.imageViewer = new Viewer(document.getElementById(this.viewerId), {
          url(image) {
            return image.ex_base64
          },
          title: [
            1,
            (image, imageData) => {
              return `${this.imageList[this.imageViewer.index].displayname} (${imageData.naturalWidth} × ${imageData.naturalHeight})`
            }
          ]
        })
      }
      this.imageViewer.options.zIndex = 666666
      this.imageViewer.images = this.imageList
      this.imageViewer.length = this.imageViewer.images.length
      let idx = this.imageList.findIndex((item) => item.id === file.id)
      this.imageViewer.index = idx
      this.imageViewer.show()
    },
    viewPdf(file) {
      axios({
        url: this.url.download,
        method: 'post',
        data: { attachmentId: file.id },
        responseType: 'blob'
      }).then((response) => {
        let url = this.getObjectURL(response)
        this.pdfFile = `/static/plugins/pdfjs/web/viewer.html?file=${url}`
      })
    },
    getObjectURL(file) {
      let url = null
      if (window.createObjectURL !== undefined) {
        // basic
        url = window.createObjectURL(file)
      } else if (window.webkitURL !== undefined) {
        // webkit or chrome
        try {
          url = window.webkitURL.createObjectURL(file)
        } catch (error) {}
      } else if (window.URL !== undefined) {
        // mozilla(firefox)
        try {
          url = window.URL.createObjectURL(file)
        } catch (error) {}
      }
      return url
    },
    close() {
      this.fileList = []
      this.pdfFile = null
    }
  }
}
</script>

<style lang="scss">
.tl-attachment-preview {
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
  min-height: 400px;
  .tree-area {
    position: absolute;
    width: 250px;
    left: 0;
    top: 0;
    height: 100%;
    border: 1px solid #cecece;
    overflow-x: scroll;
    .el-tree-node > .el-tree-node__children {
      overflow: visible;
    }
  }
  .preview-area {
    margin-left: 260px;
    height: 100%;
    border: 1px solid #cecece;
    overflow-x: scroll;
    overflow-y: hidden;
  }
  .bg-title {
    height: 36px;
    line-height: 36px;
    background: #efefef;
    border-bottom: 1px solid #fafafa;
    padding-left: 10px;
  }
}
</style>
